using System.Data;
using System.Linq;
using System.Security.Principal;
using WebMatrix.WebData;

namespace Home.Site.Models.Account
{
    public class AccountRepository : IAccountRepository
    {
        private readonly UsersContext context = new UsersContext();

        public UserProfile GetUserById(int userId)
        {
            return context.UserProfiles.FirstOrDefault(u => u.UserId == userId);
        }

        public void Save(UserProfile model)
        {
            context.Entry(model).State = EntityState.Modified;
            context.SaveChanges();
        }

        public void BuildUser(LocalPasswordModel model, UserProfile user)
        {
            user.ShowName = model.ShowName != null
                                ? model.ShowName.Length < 50 ? model.ShowName : model.ShowName.Substring(0, 50)
                                : "";
            user.Email = model.Email != null ? model.Email.Length < 20 ? model.Email : model.Email.Substring(0, 20) : "";
            user.Other = model.Other != null ? model.Other.Length < 500 ? model.Other : model.Other.Substring(0, 500) : "";
        }

        public LocalPasswordModel GetLocalUserById(int userId)
        {
            var user = context.UserProfiles.FirstOrDefault(u => u.UserId == userId);
            if (user != null)
                return new LocalPasswordModel
                    {
                        UserName = user.UserName,
                        Email = user.Email,
                        ShowName = user.ShowName,
                        Other = user.Other,
                        Gravatar = user.Gravatar,
                        LastName = user.LastName,
                        IsAdmin = user.IsAdmin,
                        IsOperator = user.IsOperator,
                        IsRoot = user.IsRoot                        
                    };
            return null;
        }

        public IQueryable<UserProfile> All()
        {
            return context.UserProfiles;
        }

        public UserProfile Find(int id)
        {
            return context.UserProfiles.Find(id);
        }

        public UserProfile GetUser(IPrincipal currentUser)
        {
            return context.UserProfiles.FirstOrDefault(u=>u.UserName==currentUser.Identity.Name);
        }

        public UserProfile GetUserByLogin(string login)
        {
            return context.UserProfiles.FirstOrDefault(u => u.UserName == login);
        }
    }
}